package com.KA.controller;

import com.KA.common.R;
import com.KA.common.SystemConstant;
import com.KA.entity.User;
import com.KA.service.UserService;
import com.KA.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户控制类")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private Environment environment;

    @Autowired
    private HttpClientUtil httpClientUtil;


    @ApiOperation("微信登录")
    @PostMapping("/wxLogin")
    public R<HashMap<String, String>> wxLogin(@RequestBody User userInfo) throws Exception {

        String jscode2sessionUrl = environment.getProperty("weixin.jscode2sessionUrl")
                                 + "?appid=" + environment.getProperty("weixin.appid")
                                 + "&secret=" +environment.getProperty("weixin.secret")
                                 + "&js_code="
                                 + userInfo.getCode()
                                 + "&grant_type=authorization_code";
        String result = httpClientUtil.sendHttpGet(jscode2sessionUrl);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.get("openid").toString();

        //远程调用微信那边的方法，就能从结果中获取用户独一无二的ipenid
        System.out.println("wxLogin方法openid:"+openid);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, openid);
        User user = userService.getOne(queryWrapper);

        //如果用户不存在数据库，则自动注册
        if (user == null) {
            userInfo.setId(UUID.randomUUID().toString());
            userInfo.setOpenid(openid);
            userInfo.setStatus(1);
            userInfo.setCreateTime(LocalDateTime.now());
            try {
                userService.saveuser(userInfo);
            }catch (Exception e){
                System.out.println("增加失败"+e);
                return R.error("增加失败"+e.toString());
            }
        } else {
            user.setNickName(userInfo.getNickName());
            user.setAvatarUrl(userInfo.getAvatarUrl());
            userService.updateById(user);
        }

        User one = userService.getOne(queryWrapper);
        String userId = one.getId().toString();
        String phone = one.getPhone();

        String token = JwtUtils.createJWT(userId, userInfo.getNickName(), SystemConstant.JWT_TTL);
        Claims claims = JwtUtils.parseJWT(token);
        System.out.println("token:"+token);
        String id = claims.getId();
        System.out.println("wxLogin方法:"+"userId" + id);
        HashMap<String,String> map = new HashMap<>();
        map.put("token",token);
        map.put("phone",phone);

        return R.success(map);

    }

    @ApiOperation("获取手机号")
    @PostMapping("wxGetPhone")
    public R<JSONObject> wxGetPhone(@RequestBody User userInfo) {
        String code = userInfo.getCode();
        System.out.println("code--" + code);
        String token_url = environment.getProperty("weixin.getAccessTokenUrl") + "appid=" + environment.getProperty("weixin.appid") + "&secret=" + environment.getProperty("weixin.secret");
        System.out.println("token_url--" + token_url);
        String token = httpClientUtil.sendHttpGet(token_url);
        System.out.println("token--" + token);

        String access_token = JSON.parseObject(token).get("access_token").toString();
        System.out.println("access_token--" + access_token);
        String url = environment.getProperty("weixin.getPhoneNumberUrl") + access_token;
        System.out.println("url--" + url);

        JSONObject params = new JSONObject();
        params.put("code", code);
        String result = httpClientUtil.sendHttpPostJson(url, params);
        JSONObject parse = (JSONObject) JSON.parse(result);
        System.out.println(parse);
        Object phone_info = parse.get("phone_info");
        System.out.println(phone_info);
        JSONObject phoneInfo = (JSONObject) JSON.parse(String.valueOf(phone_info));
        String phoneNumber = (String) phoneInfo.get("phoneNumber");
        System.out.println(phoneNumber);
        System.out.println("UserId" + UserThreadLocal.get().getId());
        User byId = userService.getById(UserThreadLocal.get().getId());
        if (!byId.getPhone().equals(phoneNumber)){
            byId.setPhone(phoneNumber);
            userService.updateById(byId);
        }
        return R.success(parse);
    }




    @ApiOperation("根据手机号获取用户信息")
    @GetMapping("/getUserInfo/{phone}")
    public R<User> getUserInfo(@PathVariable String phone) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(phone != null, User::getPhone, phone);
        User byId = userService.getOne(queryWrapper);
        if (byId != null) {
            return R.success(byId);
        }
        return R.error("用户信息查询失败！");

    }



    @GetMapping("/getUserCount")
    public R<Long> getUserCount() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        long count = userService.count(queryWrapper);
        return R.success(count);
    }



    /**
     * 修改页面，根据ID回显数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<User> getById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user != null) {
            return R.success(user);
        }
        return R.error("没有查询到对应会员信息");
    }


}
